<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

use app\common\enum\FileEnum;
use app\common\model\FileModel;
use think\exception\ValidateException;
use think\facade\Filesystem;
use util\StringUtil;

/**
 * 文件处理逻辑
 */
class FileLogic extends BaseLogic
{

    public function base64Upload($image_base64_content){
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $image_base64_content, $result)){
            $type = $result[2];
            if(!in_array($type,['jpg','jpeg','png','gif'])){
                $this->error = '上传的文件不合法！';
                return false;
            }
            $file_path = PATH_PICTURE.'base64/'.date('Ymd',time())."/";
            if(!file_exists($file_path)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($file_path, 0755, true);
            }
            $image_content = base64_decode(str_replace($result[1], '', $image_base64_content));
            $file_name = md5($image_content).".{$type}";
            $md5 = md5($image_content);
            $new_file = $file_path.$file_name;
            $picture_info = FileModel::instance()->field('id,name,path,md5')->where('md5',$md5)->find();
            if (!empty($picture_info)) { return $picture_info; }

            if (file_put_contents($new_file, $image_content)){
                //保存成功
                $data = ['name' => $file_name, 'path' => str_replace(PATH_PICTURE,'',$new_file),'full_path'=>$new_file, 'md5' => $md5,'type'=>FileEnum::PICTURE];
                $result = FileModel::create($data);
                if ($result) { $data['id'] = $result; return $data; }
                return  false;
            }else{
                $this->error = "文件保存失败";
                return false;
            }
        }else{
            $this->error = "上传的文件不是base64文件";
            return false;
        }
    }
    
    /**
     * 图片上传
     * small,medium,big
     */
    public function pictureUpload($name = 'image')
    {
        $object_info = request()->file($name);
        $md5  = $object_info->md5();
        $picture_info = FileModel::instance()->field('id,name,path,md5')->where('md5',$md5)->find();
        if (!empty($picture_info)) { return $picture_info; }
        try{
            $rule = 'image';
            if(config('config.file_size')){
                $rule .= '|fileSize:'.(config('config.file_size') * 1024);
            }
            if(config('config.file_ext')){
                $rule .= '|fileExt:'.config('config.file_ext');
            }
            validate([$name=>$rule])
                ->check([$name=>$object_info]);
            $save_name = Filesystem::putFile('picture',$object_info);
            $save_name = StringUtil::instance()->sr($save_name,'\\','/');
            list($picture_path,$date_name,$file_name) = StringUtil::instance()->strToArr($save_name,'/');
            $defaultDriver = config('filesystem.default');
            $driverInfo = config('filesystem.disks.'.$defaultDriver);
            if(!isset($driverInfo['url'])){
                $full_path = $driverInfo['root'].'/'.$save_name;
                $full_path = StringUtil::instance()->sr($full_path,'\\','/');
                $path = (string) url('admin/File/fileOutput',['full_path'=>$full_path]);
            }else {
                $path = $driverInfo['url'] . '/' . $save_name;
                $full_path = $driverInfo['root'].'/'.$save_name;
                $full_path = StringUtil::instance()->sr($full_path,'\\','/');
            }
            $data = ['name' => $file_name, 'path' => $path,'full_path'=>$full_path, 'md5' => $md5,'type'=>FileEnum::PICTURE];
            $result = FileModel::create($data);
            $id = $result->id;
            unset($object);
            if ($result) {
                $data['id'] = $id;
                return $data;
            }
            return '上传失败';
        }catch (ValidateException $e){
            return $e->getMessage();
        }
    }
    
    /**
     * 文件上传
     */
    public function fileUpload($name = 'file')
    {
        $object_info = request()->file($name);
        $md5  = $object_info->md5();
        $picture_info = FileModel::instance()->field('id,name,path,md5')->where('md5',$md5)->find();
        if (!empty($picture_info)) { return $picture_info; }
        try{
            $rule = 'file';
            if(config('config.file_size')){
                $rule .= '|fileSize:'.(config('config.file_size') * 1024);
            }
            if(config('config.file_ext')){
                $rule .= '|fileExt:'.config('config.file_ext');
            }
            validate([$name=>$rule])
                ->check([$name=>$object_info]);
            $save_name = Filesystem::putFile('file',$object_info);
            $save_name = StringUtil::instance()->sr($save_name,'\\','/');
            list($file_path,$date_name,$file_name) = StringUtil::instance()->strToArr($save_name,'/');
            $defaultDriver = config('filesystem.default');
            $driverInfo = config('filesystem.disks.'.$defaultDriver);
            if(!isset($driverInfo['url'])){
                $full_path = $driverInfo['root'].'/'.$save_name;
                $full_path = StringUtil::instance()->sr($full_path,'\\','/');
                $path = (string) url('admin/File/fileOutput',['full_path'=>$full_path]);
            }else {
                $path = $driverInfo['url'] . '/' . $save_name;
                $full_path = $driverInfo['root'].'/'.$save_name;
                $full_path = StringUtil::instance()->sr($full_path,'\\','/');
            }
            $data = ['name' => $file_name, 'path' => $path,'full_path'=>$full_path, 'md5' => $md5,'type'=>FileEnum::FILE];
            $result = FileModel::create($data);
            $id = $result->id;
            unset($object);
            if ($result) {
                $data['id'] = $id;
                return $data;
            }
            return '上传失败';
        }catch (ValidateException $e){
            return $e->getMessage();
        }
    }

    /**
     * 获取指定目录下的所有文件
     * @param null $path
     * @return array
     */
    public function getFileByPath($path = null)
    {
        $dirs = new \FilesystemIterator($path);
        $arr = [];
        foreach ($dirs as $v)
        {
            if($v->isdir())
            {
                $_arr = $this->getFileByPath($path ."/". $v->getFilename());
                $arr = array_merge($arr,$_arr);
            }else{
                $arr[] = $path . "/" . $v->getFilename();
            }
        }
        return $arr;
    }

    public function checkPictureExists($param = []) {
        return FileModel::instance()->where('md5',$param['md5'])->find();
    }

    public function checkFileExists($param = []) {
        return FileModel::instance()->where('md5',$param['md5'])->find();
    }
}
